package com.eventx.config;

import com.eventx.bus.config.EventConfigItem;
import com.eventx.service.def.DefaultChannelConfig;
import com.eventx.service.def.DefaultChannelProvider;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: anrror
 **/
@Configuration
@ConditionalOnProperty(prefix = "spring.eventx.def", value = "enable", havingValue = "true")
@EnableConfigurationProperties({DefaultChannelConfig.class})
public class EventConfigManager  implements InitializingBean {

    private static Map<String, EventConfigItem> subscriberItemConcurrentHashMap = new ConcurrentHashMap<String,EventConfigItem>();

    private static String DEFAULT_CHANNEL = "DEFAULT_CHANNEL";


    @Override
    public void afterPropertiesSet() {
        EventConfigItem eventSubcriberConfigItem = new EventConfigItem();
        eventSubcriberConfigItem.setEventName(DEFAULT_CHANNEL);
        eventSubcriberConfigItem.setChannelProvider(new DefaultChannelProvider());
        addEventSubcriberConfigItem(eventSubcriberConfigItem);
    }


    public static void addEventSubcriberConfigItem(EventConfigItem eventSubcriberConfigItem){
        subscriberItemConcurrentHashMap.put(eventSubcriberConfigItem.getEventName(),eventSubcriberConfigItem);
    }

    public static EventConfigItem get(String eventName){
        EventConfigItem eventSubcriberConfigItem = subscriberItemConcurrentHashMap.get(eventName);
        if(eventSubcriberConfigItem == null){
            eventSubcriberConfigItem = subscriberItemConcurrentHashMap.get(DEFAULT_CHANNEL);
        }
        return eventSubcriberConfigItem;
    }

}
